/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 */


import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;

/**
 *
 * @author xuela
 */
public class Editor {

    public static final JTextArea tip = new JTextArea();

    public static void main(String[] args) {
        Editor.saved(args[0]);
        
        JMenuBar edit = new JMenuBar();
        JMenu menu = new JMenu(args[0]);

        Editor.tip.setEditable(false);
        Editor.tip.setLineWrap(true);

        JMenuItem writen = new JMenuItem("writen");
        menu.add(writen);
        writen.addActionListener(e -> Editor.tip.setEditable(true));

        JMenuItem readen = new JMenuItem("readen");
        menu.add(readen);
        readen.addActionListener(e -> Editor.tip.setEditable(false));

        JMenuItem saved = new JMenuItem("saved");
        menu.add(saved);
        saved.addActionListener(e -> {
            Editor.saved(args[0]);
            System.exit(0);
        });

        edit.add(menu);

        JFrame frame = new JFrame();

        frame.setSize(480, 300);

        frame.setJMenuBar(edit);

        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(Editor.tip);

        Editor.setText(args[0]);
        Editor.tip.updateUI();
    }

    public static void setText(String filename) {
        try (FileInputStream stream = new FileInputStream(filename)) {
            Editor.tip.setText(new String(stream.readAllBytes()));
        } catch (IOException ex) {
            Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void saved(String filename) {
        try (FileWriter writer = new FileWriter(filename)) {
            writer.write(Editor.tip.getText());
        } catch (IOException ex) {
            Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
